﻿using log4net;
using log4net.Repository.Hierarchy;
using MySql.Data.MySqlClient;
using server.Model;
using server.Tool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace server.DAO
{
    public class KnapsackDao : CommonDao
    {
        ILog Logger = log4net.LogManager.GetLogger("server.DAO.KnapsackDao");

        private LifeDao lifeDao = new LifeDao();
        public List<Knapsack_Info> GetKnapsackInfo(string grounpId)
        {

            string sql = "select * from knapsack_info where game_id = @game_id ORDER BY id desc";
            List<Knapsack_Info> result = MySqlExecuteTools.GetObjectResult<Knapsack_Info>(sql,
                new MySqlParameter[] { new MySqlParameter("@game_id", grounpId) });
            result.ForEach((item) => {
                item .knapsack =  MySqlExtendTools.GetEntityObjectByPrimaryKey<Knapsack>(item.knapsack_id.ToString(), "knapsack");

            });

            return  result;
        }

        public string DeleteKnapsack(string Id)
        {
            string sql = "delete from knapsack_info where id = " + Id;
            MySqlExecuteTools.AddOrUpdate(sql);
            //关联删除
            sql = "delete from knapsack_detail where knapsack_info_id = " + Id;
            MySqlExecuteTools.AddOrUpdate(sql);
            return "0";
        }

        public string SaveKnapsackInfo(string gameId, string knapsack_id, string startTime, string endTime, string count,string addCountValue)
        {
            //string sql = "select * from knapsack_info where game_id = @game_id";
            //List<Knapsack_Info> list = MySqlExecuteTools.GetObjectResult<Knapsack_Info>(sql, new MySqlParameter[] { new MySqlParameter("@game_id", gameId) });
            //int _startTime = Convert.ToInt16(startTime);
            //int _endTime = Convert.ToInt16(endTime);
            //for (int i=0;i< list.Count;i++)
            //{
            //   if(_startTime >= list[i].startTime  && _startTime<= list[i].endTime)
            //    {
            //        return "-1";
            //    }

            //    if (_endTime >= list[i].startTime && _endTime <= list[i].endTime)
            //    {
            //        return "-1";
            //    }
            //}
       
           string sql = "insert into knapsack_info(game_id,knapsack_id,startTime,endTime,count,addCountValue) " +
                   "values('" + gameId + "','" + knapsack_id + "','" + startTime + "','" + endTime + "','" + count + "','" + addCountValue + "')";

            MySqlExecuteTools.AddOrUpdate(sql);

            return "0";
        }

        public long SaveKnapsackInfoById(string gameId, string knapsack_id, string startTime, string endTime, string count, string addCountValue)
        {
            string sql = "insert into knapsack_info(game_id,knapsack_id,startTime,endTime,count,addCountValue) " +
                  "values('" + gameId + "','" + knapsack_id + "','" + startTime + "','" + endTime + "','" + count + "','" + addCountValue + "')";

            return MySqlExecuteTools.GetAddID(sql);
        }

        public string ModifyKnapsackInfo(string id, string knapsack_id, string startTime, string endTime, string count,string gournpId,string addCountValue)
        {
            string sql = "select * from knapsack_info where game_id = @game_id and id<>"+ id;
            //List<Knapsack_Info> list = MySqlExecuteTools.GetObjectResult<Knapsack_Info>(sql, new MySqlParameter[] { new MySqlParameter("@game_id", gournpId) });
            //int _startTime = Convert.ToInt16(startTime);
            //int _endTime = Convert.ToInt16(endTime);
            //for (int i = 0; i < list.Count; i++)
            //{
            //    if (_startTime >= list[i].startTime && _startTime <= list[i].endTime)
            //    {
            //        return "-1";
            //    }

            //    if (_endTime >= list[i].startTime && _endTime <= list[i].endTime)
            //    {
            //        return "-1";
            //    }
            //}


            sql = "update knapsack_info set knapsack_id = '" + knapsack_id + "', startTime = '" + startTime +
               "', endTime = '" + endTime + "', count = '" + count + "', addCountValue = '" + addCountValue + "' where id = "+ id;
            MySqlExecuteTools.AddOrUpdate(sql);
            return "0";

        }

        public void DeleteKnapsackByGameId(string grounpId)
        {
            string sql = "delete from knapsack_info where game_id = " + grounpId;
            MySqlExecuteTools.AddOrUpdate(sql);
            //关联删除
            sql = "delete from knapsack_detail where game_id = " + grounpId;

            MySqlExecuteTools.AddOrUpdate(sql);
        }




        public string GetKnapsackById(string id)
        {
            Knapsack_Info knapsack_Info =  MySqlExtendTools.GetEntityObjectByPrimaryKey<Knapsack_Info>(id, "knapsack_info");
            return Utils.CollectionsConvert.ToJSON(knapsack_Info);

        }

        internal List<Knapsack_Detail> GetKnapsackDetailList(string game_id)
        {
            string sql = "select * from knapsack_detail where game_id = @game_id ORDER BY id desc";
            List<Knapsack_Detail> result = MySqlExecuteTools.GetObjectResult<Knapsack_Detail>(sql,
                new MySqlParameter[] { new MySqlParameter("@game_id", game_id) });

            result.ForEach((item) => {

                Knapsack_Info knapsack_Info = MySqlExtendTools.GetEntityObjectByPrimaryKey<Knapsack_Info>(item.knapsack_info_id.ToString(), "knapsack_info");

                if(knapsack_Info!=null)
                {
                    item.knapsack = MySqlExtendTools.GetEntityObjectByPrimaryKey<Knapsack>(knapsack_Info.knapsack_id.ToString(), "knapsack");
                }
                
            });
            //Console.WriteLine(Utils.CollectionsConvert.ToJSON(result));
            return result;


        }

      
        internal string GetKnapsackInfoCount(string grounpId)
        {
            string sql = "select * from knapsack_info where game_id = @game_id ORDER BY id desc";
            int count  = MySqlExecuteTools.GetCountResult(sql,
                new MySqlParameter[] { new MySqlParameter("@game_id", grounpId) });

            return count.ToString();
        }

        internal string SaveKnapsackDetail(List<Knapsack_Detail> list,bool isDelete = true)
        {

            int gameId = 0;
            string sql = "";
            if (list.Count>0 && isDelete)
            {
                gameId = list[0].game_id;
                //先删除
                sql = "delete from knapsack_detail where game_id = " + gameId;
                MySqlExecuteTools.AddOrUpdate(sql);

            }
            string json = Utils.CollectionsConvert.ToJSON(list);
            //Logger.InfoFormat("SaveKnapsackDetail={0} ", json);
            list.ForEach((item) => {

                int id = item.knapsack_info_id;
                float lat = item.lat;
                float lon = item.lon;
                gameId = item.game_id;
                sql = "insert into knapsack_detail(game_id,knapsack_info_id,lat,lon) " +
                   "values('" + gameId + "','" + id + "','" + lat + "','" + lon + "')";
                 MySqlExecuteTools.GetAddID(sql);

            });

            return "";

        }

        public List<Knapsack> GetKnapsackList()
        {
            // throw new NotImplementedException();
            string sql = "select * from knapsack";
            List<Knapsack> knapsackList = MySqlExecuteTools.GetObjectResult<Knapsack>(sql, null);

            return knapsackList;
        }

        /// <summary>
        /// 在获取设备后销毁
        /// </summary>
        /// <param name="id"></param>
        public void DeleteKnapsack_DetailById(int id)
        {
            string sql = "delete from knapsack_detail where id = " + id;
            MySqlExecuteTools.AddOrUpdate(sql);
        }
        /// <summary>
        /// 删除过时的Knapsack
        /// </summary>
        /// <param name="grounpId"></param>
        public void DeleteOutOfDateKnapsack(Grounp grounp)
        {
           // Grounp grounp = MySqlExtendTools.GetEntityObjectByPrimaryKey<Grounp>(grounpId.ToString(), "grounp");
            float realTime = grounp.playerTime - grounp.remainTime / 60;
            string sql = "select * from knapsack_info where game_id = @game_id and endTime<" + realTime;
            List<Knapsack_Info> result = MySqlExecuteTools.GetObjectResult<Knapsack_Info>(sql,
                new MySqlParameter[] { new MySqlParameter("@game_id", grounp.id) });
            result.ForEach((item)=> {

                sql = "delete from knapsack_detail where knapsack_info_id = " + item.id;
                MySqlExecuteTools.AddOrUpdate(sql);
                sql = "delete from knapsack_info where id = " + item.id;
                MySqlExecuteTools.AddOrUpdate(sql);

            });
        }

        /// <summary>
        /// 获取该时间段内所有的Knapsack_Detail 推送到前台
        /// </summary>
        /// <param name="grounpId"></param>
        /// <returns></returns>
        public List<Knapsack_Detail> GetTimeInKnapsack(Grounp grounp)
        {
            //Grounp grounp = MySqlExtendTools.GetEntityObjectByPrimaryKey<Grounp>(grounpId.ToString(), "grounp");
            //Console.WriteLine("get"+DateTime.Now);
            
            float realTime = grounp.playerTime -  grounp.remainTime / 60;
            string sql = "select * from knapsack_info where game_id = @game_id and startTime<=" + realTime + " and endTime>=" + realTime;
            List<Knapsack_Info> knapsackInfoList = MySqlExecuteTools.GetObjectResult<Knapsack_Info>(sql,
                new MySqlParameter[] { new MySqlParameter("@game_id", grounp.id) });

            List<Knapsack_Detail> result = new List<Knapsack_Detail>();
            List<int> ids = new List<int>();
            if(knapsackInfoList!=null && knapsackInfoList.Count>0)
            {
                knapsackInfoList.ForEach((item) => {

                    sql = "select * from knapsack_detail where knapsack_info_id = " + item.id;
                    List<Knapsack_Detail> knapsack_DetailResult = MySqlExecuteTools.GetObjectResult<Knapsack_Detail>(sql, null);

                    Knapsack knapsack = MySqlExtendTools.GetEntityObjectByPrimaryKey<Knapsack>(item.knapsack_id.ToString(), "knapsack");
                    knapsack_DetailResult.ForEach((_item) => {

                        _item.knapsack = knapsack;
                        _item.addCountValue = MySqlExtendTools.GetEntityObjectByPrimaryKey<Knapsack_Info>(_item.knapsack_info_id.ToString(), "Knapsack_Info").addCountValue;
                        ids.Add(_item.id);
                    });
                    result.AddRange(knapsack_DetailResult);

                    //重置变量
                    sql = "update knapsack_detail set state = 0 where knapsack_info_id = " + item.id;
                    MySqlExecuteTools.AddOrUpdate(sql);

                });
            }
           
            return result;

        }

        //private int AddLifeCount = 10;

        //private int AddBulletCount = 5;
        /// <summary>
        /// 获取到背包物资进行确认
        /// </summary>
        /// <param name="userKnapsack"></param>
        public void LocateKnapsackDetailConfirm(UserKnapsack userKnapsack)
        {
          //  Console.WriteLine("confirm"+DateTime.Now);
            Logger.Debug(Utils.CollectionsConvert.ToJSON(userKnapsack));
            int userId = userKnapsack.userId;
           Knapsack_Detail item = userKnapsack.knapsackDetail;
            int result = 0;
            bool resultFlag = false;
            int gameId = 0;
            UserItem userNameItem = MySqlExtendTools.GetEntityObjectByPrimaryKey<UserItem>(userId.ToString(), "user");

            Knapsack_Detail knapsack_Detail_Item = MySqlExtendTools.GetEntityObjectByPrimaryKey<Knapsack_Detail>(item.id.ToString(), "knapsack_detail");

            if (knapsack_Detail_Item != null)
            {
                gameId = item.game_id;
                Knapsack knapsack = item.knapsack;
                int addCount = MySqlExtendTools.GetEntityObjectByPrimaryKey<Knapsack_Info>(knapsack_Detail_Item.knapsack_info_id.ToString(), "knapsack_info").addCountValue;
                //急救
                if (knapsack.type == 0)
                {

                    lifeDao.SetLifeValue(userId.ToString(), addCount, false);
                }
                //增加弹量或则增加金币
                else if (knapsack.type == 1 || knapsack.type==3)
                {
                    string sql = "select * from life where userId = @userId";
                    List<Life> lifes = MySqlExecuteTools.GetObjectResult<Life>(sql, new MySqlParameter[] { new MySqlParameter("@userId", userId) });
                    if (lifes.Count > 0)
                    {
                        Life life = lifes.FirstOrDefault<Life>();
                        if(knapsack.type == 1)
                        {
                            //增加弹量
                            if (life.bulletCount <= 0)
                            {
                                lifeDao.PublishBulletData(userNameItem.name, userId.ToString(), GetRoomNameByUerId(userId.ToString()), false);
                            }
                            //AddBulletCount = 
                            sql = "update  life set bulletCount  =" + (life.bulletCount + addCount) + " where id = " + life.id;
                        }

                        else if(knapsack.type == 3)
                        {
                            sql = "update  life set goldCoin  =" + (life.goldCoin + addCount) + " where id = " + life.id;
                        }
                           
                        MySqlExecuteTools.AddOrUpdate(sql);

                    }
                     
                       
                }
                //无敌
                else if (knapsack.type == 2)
                {

                }

                result = knapsack.type;
                resultFlag = true;
                //删除
                MySqlExtendTools.DeleteByPrimaryKey(knapsack_Detail_Item.id, "knapsack_detail");
            }
           
            //通知
            if (resultFlag)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                dic.Add("type", result);
                dic.Add("userId", userId);
                dic.Add("userName", userNameItem.name);

                string sql = "select * from room_user where user_id = @user_id";
                List<Room_User> room_UserList = MySqlExecuteTools.GetObjectResult<Room_User>(sql,
                   new MySqlParameter[] { new MySqlParameter("@user_id", userId) });

                if (room_UserList.Count > 0)
                {
                    int roomId = room_UserList[0].room_id;
                    Room room = MySqlExtendTools.GetEntityObjectByPrimaryKey<Room>(roomId.ToString(), "room");
                    dic.Add("roomName", room.name);
                }

                SendNoticeMessageInGrounp(userId.ToString(), dic, "LocateKnapsackDetailConfirm");
            }

        }

        public void GameFinishDelete(int grounpId)
        {
            string sql = "select * from knapsack_info where game_id = @game_id";
            List<Knapsack_Info> knapsackInfoList = MySqlExecuteTools.GetObjectResult<Knapsack_Info>(sql,
                new MySqlParameter[] { new MySqlParameter("@game_id", grounpId) });

            if (knapsackInfoList != null && knapsackInfoList.Count > 0)
            {
                knapsackInfoList.ForEach((item) => {

                    sql = "delete from knapsack_detail where knapsack_info_id = " + item.id;
                    MySqlExecuteTools.AddOrUpdate(sql);
                    sql = "delete from knapsack_info where id = " + item.id;
                    MySqlExecuteTools.AddOrUpdate(sql);

                });
            }
        }

        /// <summary>
        /// 停止了无敌能量宝
        /// </summary>
        /// <param name="userId"></param>
        internal void StopEnergyTips(string userId)
        {
            UserItem userNameItem = MySqlExtendTools.GetEntityObjectByPrimaryKey<UserItem>(userId.ToString(), "user");
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("userName", userNameItem.name);

            string sql = "select * from room_user where user_id = @user_id";
            List<Room_User> room_UserList = MySqlExecuteTools.GetObjectResult<Room_User>(sql,
               new MySqlParameter[] { new MySqlParameter("@user_id", userId) });

            if (room_UserList.Count > 0)
            {
                int roomId = room_UserList[0].room_id;
                Room room = MySqlExtendTools.GetEntityObjectByPrimaryKey<Room>(roomId.ToString(), "room");
                dic.Add("roomName", room.name);
            }

            SendNoticeMessageInGrounp(userId.ToString(), dic, "StopEnergy");
        }


    }
}
